package com.yqs.JavaWeb;

import com.yqs.JavaWeb.util.DBConnection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @project: JavaWeb
 * @package: com.yqs.JavaWeb
 * @Description:
 * @Since: jdk版本号
 * @Author: 逝风岁月
 * @Email: 2637182317@qq.com
 * @Date: 2024-09-11 17:09:20
 */

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        response.setContentType("text/html;charset=UTF-8");

        if (username != null && password != null) {
            try (Connection conn = DBConnection.getConnection()) {
                String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
                PreparedStatement pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, username);
                pstmt.setString(2, password);

                ResultSet rs = pstmt.executeQuery();
                if (rs.next()) {
                    response.getWriter().println("登录成功！");
                } else {
                    PrintWriter writer = response.getWriter();
                    writer.println("<script>alert('登录失败！');location.href='login.jsp';</script>");
                }
            } catch (SQLException e) {
                e.printStackTrace();
                response.getWriter().println("登录失败：" + e.getMessage());
            }
        } else {
            response.getWriter().println("请填写所有字段！");
        }
    }
}